package com.example.utils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

/** 
 * CookieUtil<br/>
 * 创建人:alvin<br/>
 * 时间：2018年11月28日-下午4:01:06 <br/>
 * @version 1.0.0<br/>
 *
 */
public class CookieUtil {

	private final static String COOKIE_NAME = "zly_login_token";

	/***
	 * 读取Cookie <br/>
	 * 方法名：readLoginToken<br/>
	 * 创建人：alvin <br/>
	 * 时间：2018年11月28日-下午3:59:16 <br/>
	 * @param request
	 * @return String<br/>
	 * @exception <br/>
	 * @since  1.0.0<br/>
	 */
	public static String readLoginToken(HttpServletRequest request) {
		Cookie[] cks = request.getCookies();
		if (cks != null) {
			for (Cookie ck : cks) {
				if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
					return ck.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * 写入Cookie <br/>
	 * 方法名：writeLoginToken<br/>
	 * 创建人：alvin <br/>
	 * 时间：2018年11月28日-下午3:58:54 <br/>
	 * @param response
	 * @param token void<br/>
	 * @exception <br/>
	 * @since  1.0.0<br/>
	 */
	public static void writeLoginToken(HttpServletResponse response, String token) {
		Cookie ck = new Cookie(COOKIE_NAME, token);
		// ck.setDomain(COOKIE_DOMAIN);
		ck.setPath("/");// 代表设置在根目录
		ck.setHttpOnly(true);
		// 单位是秒。
		// 如果这个maxage不设置的话，cookie就不会写入硬盘，而是写在内存。只在当前页面有效。
		ck.setMaxAge(60 * 60 * 24 * 7);// 如果是-1，代表永久
		response.addCookie(ck);
	}

	/**
	 * 清除Cookie<br/>
	 * 方法名：delLoginToken<br/>
	 * 创建人：alvin <br/>
	 * 时间：2018年11月28日-下午3:58:09 <br/>
	 * @param request
	 * @param response void<br/>
	 * @exception <br/>
	 * @since  1.0.0<br/>
	 */
	public static void delLoginToken(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cks = request.getCookies();
		if (cks != null) {
			for (Cookie ck : cks) {
				if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
					// ck.setDomain(COOKIE_DOMAIN);
					ck.setPath("/");
					ck.setMaxAge(0);// 设置成0，代表删除此cookie。
					response.addCookie(ck);
					return;
				}
			}
		}
	}

	/**
	 * 显示Cookie
	 * 
	 * @param request
	 * @param response
	 */
	public static void showCookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();// 这样便可以获取一个cookie数组
		if (null == cookies) {
			System.out.println("没有cookie=========");
		} else {
			for (Cookie cookie : cookies) {
				System.out.println("name:" + cookie.getName() + "\tvalue:" + cookie.getValue());
			}
		}
	}

	/**
	 * 添加Cookie 设置有效期一天
	 * 
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void addCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie;
		try {
			cookie = new Cookie(name.trim(), URLEncoder.encode(value, "UTF-8"));
			cookie.setMaxAge(60 * 60 * 24);// 设置为一天
			cookie.setPath("/NewSys");
			// System.out.println("Add =="+cookie.getName()+"\t"+cookie.getValue());
			// 把cookie存到response中，响应时将把cookie信息带回浏览器，保存到浏览器中
			response.addCookie(cookie);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 修改Cookie
	 * 
	 * @param request
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void editCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
		Cookie[] cookies = request.getCookies();
		if (null == cookies) {
			System.out.println("没有cookie==============");
		} else {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					System.out.println("原值为:" + cookie.getValue());
					cookie.setValue(value);
					cookie.setPath("/");
					cookie.setMaxAge(60 * 60 * 24);// 设置为一天
					// System.out.println("被修改的cookie名字为:"+cookie.getName()+",新值为:"+cookie.getValue());
					response.addCookie(cookie);
					break;
				}
			}
		}
	}

	/**
	 * 删除Cookie
	 * 
	 * @param request
	 * @param response
	 * @param name
	 */
	public static void delCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		Cookie[] cookies = request.getCookies();
		if (null == cookies) {
			System.out.println("没有cookie==============");
		} else {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					cookie.setValue(null);
					cookie.setMaxAge(0);// 立即销毁cookie
					cookie.setPath("/");
					// System.out.println("被删除的cookie名字为:"+cookie.getName());
					// response.addCookie(cookie);
					break;
				}
			}
		}
	}

	/**
	 * 删除所有cookies
	 * 
	 * @param request
	 * @param response
	 */
	public static void delAllCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (StringUtil.isNotEmpty(cookies + "")) {
			for (Cookie cookie : cookies) {
				if (!("JSESSIONID".equals(cookie))) {
					cookie.setMaxAge(0);// 立即销毁cookie
					cookie.setPath("/");
					// System.out.println("被删除的cookie名字为:"+cookie.getName());
					// response.addCookie(cookie);
				}
			}
		}
	}

	/**
	 * 根据Cookie名字获取 Cookie
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = ReadCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie = (Cookie) cookieMap.get(name);
			return cookie;
		} else {
			return null;
		}
	}

	/**
	 * 根据Cookie名字获取 Cookie
	 * 
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieByNameStr(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = request.getCookies();
		String cookieValue = "";
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(cookieName)) {
					cookieValue = cookie.getValue();
					break;
				}
			}
		}
		return cookieName;
	}

	public static String findCookieByName(Cookie[] cookies, String name) {
		String value = "";
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				value = URLDecoder.decode(cookie.getValue());
				break;
			} else {
				value = "";
			}
		}
		return value;
	}

	/**
	 * 读取Cookie Map
	 * 
	 * @param request
	 * @return
	 */
	private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}

}
